package com.haidechizi.i18n.code.generator.common.message.language;

import com.haidechizi.i18n.code.generator.common.message.config.GeneratorProperties;
import com.haidechizi.i18n.code.generator.common.message.constants.LanguageKeyConstants;
import com.haidechizi.i18n.code.generator.common.message.translate.ProxyTranslate;
import com.haidechizi.i18n.code.generator.common.message.utils.TranslateUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;


/**
 * 翻译对应语言的模板文件
 */
public abstract class BaseLanguage implements Language {

    @Autowired
    private ProxyTranslate translate;

    @Autowired
    private GeneratorProperties configuration;


    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        LanguageHolder.putLanguage(type(), this);
    }

    /**
     * 生成语言数据
     *
     * @param key
     * @param cnData
     * @param languageMap
     */
    @Override
    public void generateLanguage(String key, String cnData, Map<String, Map<String, String>> languageMap) {
        String data = translate(cnData);
        Map<String, String> map = languageMap.get(key);
        if (map == null) {
            map = new HashMap<>(8);
            languageMap.put(key, map);
        }
        // 将语言对应的值添加到map中
        map.put(type(), data);
    }

    /**
     * 批量翻译
     *
     * @param currentLanguage
     * @param languageMap
     * @return
     */
    @Override
    public Map<String, String> batchGenerateLanguage(String currentLanguage, Map<String, String> languageMap) {
        Map<String, String> singleMap = new HashMap<>();
        for (Map.Entry<String, String> entry : languageMap.entrySet()) {
            String translate = translate(entry.getValue(), currentLanguage);
            singleMap.put(entry.getKey(), translate);
        }
        return singleMap;
    }

    /**
     * 翻译对应的语言
     *
     * @param cnData
     * @return
     */
    protected String translate(String cnData) {
        if (configuration.isZhUseLocal()) {
            String language = type();
            if (LanguageKeyConstants.ZH_CN.equals(language) || LanguageKeyConstants.ZH_HK.equals(language)) {
                return TranslateUtils.translate(cnData, language);
            }
        }
        return translate.translate(cnData, type());
    }

    /**
     * 翻译对应的语言
     *
     * @param data
     * @param currentLanguage
     * @return
     */
    protected String translate(String data, String currentLanguage) {
        if (configuration.isZhUseLocal()) {
            String language = type();
            if (LanguageKeyConstants.ZH_CN.equals(language) || LanguageKeyConstants.ZH_HK.equals(language)) {
                return TranslateUtils.translate(data, language);
            }
        }
        return translate.translate(data, currentLanguage, type());
    }
}
